import { Component, OnInit, Renderer2 } from '@angular/core';
import {
  myCollectionsObject,
  AuthGuardService,
  tabListObject,
} from '../@core/auth-guard-service.guard';
import { LoadingService } from 'ng-devui/loading';
import { DialogService } from 'ng-devui/modal';
import { DocumentRef } from 'ng-devui/window-ref';
import { AvatarDetailComponent } from './avatar-detail/avatar-detail.component';
import { QueryParams } from '../@core/interface/manage';
import { ToastService } from 'ng-devui';
import { Router } from '@angular/router';
@Component({
  selector: 'app-collections',
  templateUrl: './collections.component.html',
  styleUrls: ['./collections.component.scss'],
})
export class CollectionsComponent implements OnInit {
  userId = parseInt(localStorage.getItem('userId'));
  queryParams: QueryParams = {
    page: 1,
    pageSize: 10,
    userId: this.userId
  }
  total = 0;

  constructor(
    private authGuardService: AuthGuardService,
    private loadingService: LoadingService,
    private dialogService: DialogService,
    private documentRef: DocumentRef,
    private renderer: Renderer2,
    private toastService: ToastService,
    private router: Router
  ) { }

  public currShowCollectionInfo: myCollectionsObject;
  public domainAccount: string = this.authGuardService.userUid;
  myCollections: myCollectionsObject[] = [];
  scrollTop: number;
  tabActiveId: string | number = 'tab1';
  activeTabData;
  showLoading: any;

  ngOnInit(): void {
    this.queryUserAllAssets();
    if (this.authGuardService.isHrefExistCode) {
      this.authGuardService.initPageInfo(() => {
        this.queryUserAllAssets();
      })
    }
  }
  showCollectionDetail(e) {
    this.currShowCollectionInfo = e;
    this.router.navigate(['./collections/collection'],
      {
        queryParams:
        {
          collectionIndex: this.currShowCollectionInfo.numberNo,
          tokenId: this.currShowCollectionInfo.token
        }
      })
  }

  queryUserAllAssets() {
    //查询当前域账户下所有藏品
    this.showLoading = this.loadingService.open();
    this.authGuardService.queryUserAllAssets(this.queryParams).subscribe(
      (succRes) => {
        if (Array.isArray(succRes.data.assets) && succRes.data.assets.length) {
          this.total = succRes.data.totalNum;
          let arr = [];
          succRes.data.assets.forEach((item) => {
            const resultArr: Array<tabListObject> = [];
            arr.push({
              token: item.tokenId,
              numberNo: item.collectionIndex,
              imgSrc: item.pictureUrl,
              tabList: resultArr,
              assetId: item.assetId
            });
          });
          this.myCollections = arr;
          this.myCollections.sort(
            (a: myCollectionsObject, b: myCollectionsObject) => {
              return Number(a.numberNo) - Number(b.numberNo);
            }
          );
        }
        this.showLoading.loadingInstance.close();
        //埋点
        (window as any).onPageView('');
      },
      (errRes) => {
        //埋点
        (window as any).onPageView('');
        const MSG = errRes?.error?.message;
        this.authGuardService.showModalPanel(
          'warning',
          this.authGuardService.errorMsgReflect[MSG]
            ? this.authGuardService.errorMsgReflect[MSG]
            : '服务端错误'
        );
        this.showLoading.loadingInstance.close();
      }
    )
  }

  pageIndexChange(pageIndex) {
    this.queryParams.page = pageIndex;
    this.queryUserAllAssets();
  }

  pageSizeChange(pageSize) {
    this.queryParams.pageSize = pageSize;
    this.pageIndexChange(1);
  }

  setHtmlStyle() {
    this.scrollTop = this.documentRef.documentElement.scrollTop;
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'top',
      `-${this.scrollTop}px`
    );
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'position',
      'fixed'
    );
    this.renderer.setStyle(this.documentRef.documentElement, 'width', `100%`);
    this.renderer.setStyle(
      this.documentRef.documentElement,
      'overflow-y',
      `scroll`
    );
  }

  removeHtmlStyle() {
    this.renderer.removeStyle(this.documentRef.documentElement, 'position');
    this.renderer.removeStyle(this.documentRef.documentElement, 'width');
    this.renderer.removeStyle(this.documentRef.documentElement, 'overflow');
    this.renderer.removeStyle(this.documentRef.documentElement, 'top');
    this.documentRef.documentElement.scrollTop = this.scrollTop;
  }

  copyId(id: string) {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(id).then(() => {
        this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] });
      }, () => {
      })
    } else {
      let textArea = document.createElement("textarea");
      textArea.value = id;
      textArea.style.position = "absolute";
      textArea.style.opacity = '0';
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      new Promise((res, rej) => {
        document.execCommand('copy') ? this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] }) : rej;
        textArea.remove();
      })
    }
  }
}
